import axios from 'axios'
import MessageBox from '@/components/Message'
import router from '@/router'

const service = axios.create({
  baseURL: import.meta.env.VITE_DOMAIN + import.meta.env.VITE_BASE_URL,
  timeout: 20000 // request timeout
})

service.interceptors.request.use(
  (config) => {
    config.headers['token'] = localStorage.getItem('token')
    return config
  },
  (error) => {
    console.error(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (response.config.responseType === 'blob') {
      if (response.status !== 200) {
        MessageBox({
          message: res.message || 'Error',
          type: 'error',
          duration: 5000
        })
      }
    } else if (res.code === 401) {
      MessageBox({
        message: res.message || 'Error',
        type: 'error',
        duration: 5000
      })
      router.replace('/login?redirect=' + router.currentRoute.value.fullPath)
    } else if (res.code !== 200) {
      MessageBox({
        message: res.message || '发生未知错误！',
        type: 'error',
        duration: 5000
      })
    }
    return res
  },
  (error) => {
    console.log('err' + error) // for debug
    MessageBox({
      message: error?.message,
      type: 'error',
      duration: 5000
    })
    return Promise.reject(error)
  }
)

export default service
